package com.geekhalo.demo.mq.event.fix;

import com.geekhalo.demo.mq.event.BaseController;
import com.geekhalo.demo.mq.event.Order;
import com.geekhalo.lego.core.web.RestResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("mq/event/fix")
@Slf4j
public class SMSTimeoutEventController extends BaseController {

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    @PostMapping("paySuccessUseEvent")
    @Transactional
    public RestResult<Boolean> paySuccess(@RequestParam Long orderId, @RequestParam String token){
        // 验证 token，保障有效性
        checkToke(token);

        // 加载订单信息
        Order order = findById(orderId);
        if (order == null){
            return RestResult.success(false);
        }
        // 支付成功，更新订单状态
        order.paySuccess();
        // 将变更更新到数据库
        updateOrder(order);

        // 【核心改动点】
        // 发布自己的领域事件，其他下游逻辑直接监听事件即可
        // 增加下游处理逻辑时，无需对 此方法 进行修改
        eventPublisher.publishEvent(new OrderPaidEvent(order));
        return RestResult.success(true);
    }

}
